package cn.kgc.vue.shiro;

import cn.hutool.json.JSONUtil;
import cn.kgc.vue.response.ResponseResult;
import cn.kgc.vue.response.ResponseStatus;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author 课工场
 * @date 2024/9/23
 * @description  自定义过滤器  实现token的校验 判定用户的请求是否合法
 */
@Slf4j
public class TokenFilter extends BasicHttpAuthenticationFilter {

    //  true  请求被允许  false  拦截
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        log.info("---------isAccessAllowed-------------");
        try {
            executeLogin(request,response);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;
            httpServletResponse.setContentType("application/json;charset=utf-8");
            PrintWriter writer=null;
            try {
                writer = httpServletResponse.getWriter();
                ResponseResult responseResult = ResponseResult.fail().code(ResponseStatus.UN_AUTH).message(ResponseStatus.UN_AUTH.getMessage());
                writer.write(JSONUtil.toJsonStr(responseResult));
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }finally {
                if (writer!=null){
                    writer.close();
                }
            }
            return  false;
        }
    }


    //  执行认证
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        log.info("----------executeLogin----------------");
        // 认证token
        HttpServletRequest  httpServletRequest = (HttpServletRequest) request;
        String token = httpServletRequest.getHeader("authorization");
        if (StringUtils.isBlank(token)){
            throw  new RuntimeException("请求未认证");
        }

        //  有token  校验token的真伪
        Subject subject = getSubject(request, response);
        // string token  ->  AuthenticationToken
        JWTToken jwtToken = new JWTToken(token,request);

        subject.login(jwtToken);

        return true;
    }
}
